﻿using BasicModuleOrm.Model;
using Dapper;

namespace BasicModuleOrm.ProductRespository
{
    public class ProductDapperRespository : IProductRespository
    {
        private DapperContext _dapperContext;

        public ProductDapperRespository(DapperContext dapperContext)
        {
            _dapperContext = dapperContext;
        }

        public Product AddProduct(Product product)
        {
            //1、创建连接
            using (var connection = _dapperContext.CreateConnection())
            {
                // 2、添加商品
                connection.Execute("insert into product (Name, Price, Stock) values (@Name,@Price,@Stock)", product);

                // 3、返回商品
                return product;
            }
        }

        public void DeleteProduct(int id)
        {
            //1、创建连接
            using (var connection = _dapperContext.CreateConnection())
            {
                // 2、删除商品
                connection.Execute("delete from product where Id = @Id", new { Id = id });
            }
        }

        public IEnumerable<Product> GetAllProduct()
        {
            //1、创建连接
            using (var connection = _dapperContext.CreateConnection())
            {
                // 2、查询商品
                var products = connection.Query<Product>("select * from product").ToList();

                // 3、返回商品
                return products;
            }
        }

        public Product GetProduct(int id)
        {
            //1、创建连接
            using (var connection = _dapperContext.CreateConnection())
            {
                // 2、查询商品
                var product = connection.QuerySingleOrDefault<Product>("select * from product where Id=@Id", new { Id = id });

                // 3、返回商品
                return product;
            }
        }

        public void UpdateProduct(int id, Product product)
        {
            //1、创建连接
            using (var connection = _dapperContext.CreateConnection())
            {
                // 2、更新商品
                connection.Execute("update product set Name = @Name, Price = @Price, Stock = @Stock where Id = @Id", product);
            }
        }
    }
}
